const express = require('express')
const userRouter = require('./router/user')
const userInfoRouter = require('./router/userinfo')
const articleCateRouter = require('./router/articleCate')
const articleRouter = require('./router/article')
const bodyParser = require('body-parser')
const joi = require('joi')
const cors = require('cors')
const expressJWT = require('express-jwt')
const { jwtSecretKey } = require('./config')

const app = express()

app.use('/uploads', express.static('./uploads'))
app.use(express.urlencoded({ extended: false })) // x-www-form-urlencoded
app.use(bodyParser.json()) // application/json
app.use(cors()) // 跨域

// 处理响应失败的中间件 为 res 对象挂载一个 res.cc() 函数 在路由前声明
app.use((req, res, next) => {
  res.cc = (err, status = 0) => {
    res.send({
      status,
      msg: err instanceof Error ? err.message : err
    })
  }
  next()
})

// 配置解析token的中间件
app.use(expressJWT({
  secret: jwtSecretKey,
}).unless({ path: [/^\/api\//] }))

// 用户路由
app.use('/api', userRouter)
app.use('/my', userInfoRouter)
app.use('/articleCate', articleCateRouter)
app.use('/article', articleRouter)

// 错误中间件
app.use((err, req, res, next) => {
  if(err instanceof joi.ValidationError) {
    return res.cc(err) // return 是为了防止连续发送两个send
  } else if (err.name === 'UnauthorizedError') {
    return res.cc('token认证失败, 未经授权访问')
  }
  // 未知错误
  res.cc(err)
})

app.listen(8088, () => {
  console.log('api serve running at http://127.0.0.1:8088')
})
